package api.factioy;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import api.interceptor.HttpCacheInterceptor;
import api.interceptor.LoggingInterceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import api.utils.Constant;

/**
 * Created by Administrator on 2018-01-11.
 */

public class RetrofitFactory {
    private  Retrofit retrofit;

    public RetrofitFactory() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)        // 连接超时事件
                .readTimeout(5, TimeUnit.SECONDS)
                // 设置log拦截
                .addInterceptor(new LoggingInterceptor())
                //读取缓存设置
                .addNetworkInterceptor(new HttpCacheInterceptor())
                //缓存大小和目录
                .cache(HttpCacheInterceptor.CacheDir.setCache())
                .build();

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
           retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                   //所有的请求必须一样的base
                .baseUrl(Constant.DIYCODE)
                .build();

    }

    //  创建单例
    private static class SingletonHolder {
        private static final RetrofitFactory INSTANCE = new RetrofitFactory();
    }
    public static  Retrofit getRetrofit() {
        return SingletonHolder.INSTANCE.retrofit;
    }

}
